package baiwa.rta.dao.Impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import baiwa.rta.dao.TowersDao;
import baiwa.rta.model.TowerModel;
import baiwa.rta.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

@Repository("towersDao")
public class TowersDaoImpl implements TowersDao {

    private static final Logger logger = Logger.getLogger(TowersDaoImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public TowerModel findTowerByAddress(TowerModel towerModel) {

        String sql = "SELECT * FROM rmrmlst WHERE RLSTADDR=?";
//		System.out.println("addr " + towerModel.getAddress());
        TowerModel t = null;
        try {
            t = jdbcTemplate.queryForObject(sql, new Object[]{towerModel.getAddress()}, new TowerModelMapper());
        } catch (Exception e) {
//			System.err.println(e.getMessage());
            e.printStackTrace();
        }
        return t;
    }

    @Override
    public List<TowerModel> findTowerByCriteria(TowerModel towerModel) {

        String sql = "select * from rmrmlst where 1=1 ";

        if (null != towerModel) {
            if (StringUtils.isNotBlank(towerModel.getTower())) {
                sql = sql.concat(" and RLSTTOWER  = '" + towerModel.getTower() + "' ");
            }
            if (StringUtils.isNotBlank(towerModel.getFloor())) {
                sql = sql.concat(" and RLSTFLOOR  = '" + towerModel.getFloor() + "' ");
            }
            if (StringUtils.isNotBlank(towerModel.getUnitNo())) {
                sql = sql.concat(" and RLSTUNITNO  = '" + towerModel.getUnitNo() + "' ");
            }
            if (StringUtils.isNotBlank(towerModel.getAddress())) {
                sql = sql.concat(" and RLSTADDR  = '" + towerModel.getAddress() + "' ");
            }
        }
        
        logger.debug(sql);
        List<TowerModel> list = jdbcTemplate.query(sql, new Object[]{}, new TowerModelMapper());
        
        return CommonUtils.isNullOrEmtry(list) ? new ArrayList<TowerModel>() : list;
    }

    public class TowerModelMapper implements RowMapper<TowerModel> {

        public TowerModel mapRow(ResultSet rs, int rowNum) throws SQLException {
            TowerModel t = new TowerModel();
            t.setRoomId(rs.getInt("RLRMID"));
            t.setTower(rs.getString("RLSTTOWER"));
            t.setFloor(rs.getString("RLSTFLOOR"));
            t.setUnitNo(rs.getString("RLSTUNITNO"));
            t.setAddress(rs.getString("RLSTADDR"));
            t.setType(rs.getString("RLSTTYPE"));

            return t;
        }

    }

}
